package cn.hesion.Proxy.Cglib;
/**
 * ClassName: CglibFactory <br/>
 * Description: <br/>
 * date: 2021/12/25 22:02<br/>
 *
 * @author Hesion<br />
 * @version
 * @since JDK 1.8
 */

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * 代理工厂
 * @author: hesion
 * @create: 2021-12-25 22:02
 **/
public class CglibFactory implements MethodInterceptor {

    //要被代理的接口
    public IPersonDoService target;

    public CglibFactory() {
    }

    public CglibFactory(IPersonDoService target) {
        this.target = target;
    }

    public IPersonDoService myCGlibCreator(){
        Enhancer enhancer = new Enhancer();
        //为代理对象设置父类，即接口类字节码
        enhancer.setSuperclass(IPersonDoService.class);
        //设置回调方法
         //这里没有采用匿名内部类的方式，而是直接创建了一个类，所以直接传入this即可
        enhancer.setCallback(this);
        return (IPersonDoService) enhancer.create();

    }
    @Override
    public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable {
            System.out.println("接口方法被调用");
            method.invoke(target,args);
            System.out.println("接口方法结束");
            return null;
    }
}
